import axios, {AxiosInstance} from 'axios';
import {ElMessage} from 'element-plus';
import router, {resetgudingRoute} from '@/router'
import {getApiUrl} from '@/utils';
import {clearSession} from "@/utils/localCache";
import {closeLoading} from "@/utils/elementUtils";
import {header} from "@/api/interface";
import {AxiosResponse, InternalAxiosRequestConfig} from "axios";

// create an axios instance
const service: AxiosInstance = axios.create({
    baseURL: getApiUrl(),
    timeout: 3 * 60 * 1000,
    withCredentials: true,
})

// request请求前拦截
service.interceptors.request.use(function (config: InternalAxiosRequestConfig) {
    // 将之前所有弹出的信息框清空
    // ElMessage.closeAll();
    // 请求前写入请求头

    const headers: header = {
        "version": "1.0",
        "Authorization": "token",
        "Content-Type": "application/json; charset=UTF-8",
    };
    for (let i in headers) {
        config.headers.set(i, headers[i])
    }
    return config;
}, function (error) {
    return Promise.reject(error);
});

// request请求后拦截
service.interceptors.response.use(function (response: AxiosResponse) {
    return response
}, function (error) {
    if (error && error.response) {
        switch (error.response.status) {
            case 400:
                error.message = '请求错误(400)';
                break;
            case 401:
                error.message = '登录过期，请重新登录(401)';
                window.setTimeout(function () {
                    clearSession()
                    resetgudingRoute()
                    router.push('/index').then(r => r);
                }, 2000)
                break;
            case 403:
                error.message = '拒绝访问(403)';
                break;
            case 404:
                error.message = '请求出错(404)';
                break;
            case 408:
                error.message = '请求超时(408)';
                break;
            case 500:
                error.message = '服务器错误(500)';
                break;
            case 501:
                error.message = '服务未实现(501)';
                break;
            case 502:
                error.message = '网络错误(502)';
                break;
            case 503:
                error.message = '服务不可用(503)';
                break;
            case 504:
                error.message = '网络超时(504)';
                break;
            case 505:
                error.message = 'HTTP版本不受支持(505)';
                break;
            default:
                error.message = '连接出错(' + error.response.status + ')';
        }
    } else {
        let errorType = error.message.split(' ')[0]
        switch (errorType) {
            case "timeout":
                error.message = '请求超时';
                break;
            default:
                error.message = '连接服务器失败!'
        }
    }

    // 将之前所有弹出的信息框清空
    ElMessage.closeAll();
    closeLoading()

    return Promise.reject(error);
});

export default service